<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="bootstrap.min.css">

</head>
<body>
    <h1 class="text-center">ajax上传</h1>
    <div class="progress progress-striped active col-lg-9 col-xs-offset-1">
        <div class="progress-bar progress-bar-success" role="progressbar"
             aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"
             id="aaa">
        </div>
    </div>
    <div class="clearfix"></div>
    <form action="4.php" method="post" enctype="multipart/form-data" role="form">
        <div class="form-group" >
            <div class="col-xs-6 col-xs-offset-1">
                <input type="file" name="pic" class="form-control ">
            </div>
            <button type="submit"  class="btn btn-default">提交</button>
        </div>
    </form>
    <h3 class="text-center"></h3>
    <script type="text/javascript">
        var form = document.getElementsByTagName('form')[0];
        var aaa = document.getElementById('aaa');
        var texta = document.getElementsByTagName('h3')[0];
        form.onsubmit = function(){
            var xhr = new XMLHttpRequest();
            //FormData 会把表单的数据整体打包
            var formData = new FormData(this);
            xhr.onreadystatechange = function(){
                if(this.readyState == 4){
                    texta.innerText = 'ok';
                    console.log(this.responseText); }}
            //打印上传进度
            xhr.upload.onprogress = function(ev){
                var pre = 100*ev.loaded/ev.total;
                aaa.style.width = pre+'%';
            }
            xhr.open('post','4.php',true);
            xhr.send(formData);
            return false;//防止错误提交
        }
    </script>
</body>
</html>